﻿/*
*类名：QinMingWeixinContainer
*归属：QinMing.WeixinContainer命名空间
*用途：获取微信公众号基础access_token、基础jsapi、基础api_ticket功能
*作者：乱世刀疤
*日期：2020.05.01
*/

using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;  
using Newtonsoft.Json.Converters; 
using Newtonsoft.Json.Linq; 
using System.Data;
using System.Data.SqlClient;
using QinMing.Config;

namespace QinMing.WeixinContainer
{
    public  class QinMingWeixinContainer : System.Web.UI.Page
    {
		
		/// <summary>
        /// 获取基础access_token，用于菜单设置、微信支付等等
        /// </summary>
        public string GetAccessToken()
		{
			SqlConnection Conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
			Conn.Open();
			SqlCommand Comm = new SqlCommand();
			Comm.Connection = Conn;
			SqlDataReader dr;

			string accesstoken = "";
			Comm.CommandText = "select appid,secret,accesstoken,DATEDIFF(second, get_date, getdate()) hour_num from weixin_accesstoken ";
			dr=Comm.ExecuteReader();
			if(dr.Read())
			{
			  if(Convert.ToInt32(dr["hour_num"].ToString())<=7000)  //有效期7200秒，防止过期
			  {    
				  accesstoken = dr["accesstoken"].ToString();
				  dr.Close();
			  }
			  else
			  {
				  string strResult;
				  string strurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + dr["appid"].ToString() + "&secret=" + dr["secret"].ToString() + "";
				  try
				  {
					  HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
					  HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
					  Stream myStream = HttpWResp.GetResponseStream();
					  StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
					  StringBuilder strBuilder = new StringBuilder();
					  while (-1 != sr.Peek())
					  {
						  strBuilder.Append(sr.ReadLine());
					  }
					  strResult = strBuilder.ToString();
				  }
				  catch
				  {
					  strResult = "err";
				  }

				  JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
				  accesstoken = obj["access_token"].ToString().Replace("\"", "");
				  dr.Close();
				  Comm.CommandText = "update weixin_accesstoken set accesstoken='"+ accesstoken +"',get_date=getdate()  ";
				  Comm.ExecuteScalar();
			   }
			  
			}

			if (Conn.State == ConnectionState.Open)
			{
			   Conn.Close();
			   Conn.Dispose();
			}

			return accesstoken;
		}
		
		/// <summary>
        /// 获取基础jsapi，用于认证
        /// </summary>
		public string GetJsapi()
		{
			SqlConnection Conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
			Conn.Open();
			SqlCommand Comm = new SqlCommand();
			Comm.Connection = Conn;
			SqlDataReader dr;
			
			string ticket="";
			Comm.CommandText = "select ticket,DATEDIFF(second, get_date, getdate()) time from weixin_jsapi ";
			dr=Comm.ExecuteReader();
			if(dr.Read())
			{
				if(Convert.ToInt32(dr["time"].ToString())<=7000)
				{
					ticket=dr["ticket"].ToString();
					dr.Close();
				}
				else
				{
					string accesstoken = GetAccessToken();
					string strResult;
					string strurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken + "&type=jsapi";
					try
					{
						HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
						HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
						Stream myStream = HttpWResp.GetResponseStream();
						StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
						StringBuilder strBuilder = new StringBuilder();
						while (-1 != sr.Peek())
						{
							strBuilder.Append(sr.ReadLine());
						}
						strResult = strBuilder.ToString();
					}
					catch
					{
						strResult = "err";
					}
					JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
					ticket = obj["ticket"].ToString().Replace("\"", "");
					dr.Close();
					Comm.CommandText = "update weixin_jsapi set ticket='"+ ticket +"',get_date=getdate()  ";
					Comm.ExecuteScalar();
				}
			  
			}
			
			if (Conn.State == ConnectionState.Open)
			{
				Conn.Close();
				Conn.Dispose();
			}
			
			return ticket;
		}

		/// <summary>
        /// 获取基础api_ticket，用于卡券接口签名
        /// </summary>
		public string GetWx_cardApi_ticket()
		{
			SqlConnection Conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
			Conn.Open();
			SqlCommand Comm = new SqlCommand();
			Comm.Connection = Conn;
			SqlDataReader dr;
			
			string ticket="";
			Comm.CommandText = "select ticket,DATEDIFF(second, get_date, getdate()) time from weixin_card_apiticket ";
			dr=Comm.ExecuteReader();
			if(dr.Read())
			{
				if(Convert.ToInt32(dr["time"].ToString())<=7000)
				{
					ticket=dr["ticket"].ToString();
					dr.Close();
				}
				else
				{
					string accesstoken = GetAccessToken();
					string strResult;
					string strurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken + "&type=wx_card";
					try
					{
						HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
						HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
						Stream myStream = HttpWResp.GetResponseStream();
						StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
						StringBuilder strBuilder = new StringBuilder();
						while (-1 != sr.Peek())
						{
							strBuilder.Append(sr.ReadLine());
						}
						strResult = strBuilder.ToString();
					}
					catch
					{
						strResult = "err";
					}
					JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(strResult));
					ticket = obj["ticket"].ToString().Replace("\"", "");
					dr.Close();
					Comm.CommandText = "update weixin_card_apiticket set ticket='"+ ticket +"',get_date=getdate()  ";
					Comm.ExecuteScalar();
				}
			  
			}
			
			if (Conn.State == ConnectionState.Open)
			{
				Conn.Close();
				Conn.Dispose();
			}
			
			return ticket;
		}

	}
	
	
}